import time
import traceback

import pandas
from pymongo import MongoClient
from bson import ObjectId

dbs = {
    "mongo": {
        "host": "118.0.1.216",
        "port": 27017,
        "username": "starviews",
        "password": "HK.bianque.27017",
        "authSource": "starviews_medical"
    }
}

mongodb_ins = MongoClient(**dbs["mongo"]).starviews_medical


def do_biz():
    dats = pandas.read_excel("./12-23.xlsx")
    row_len = len(dats.index.values)
    for i in range(row_len):
        row_dat = dats.loc[i].values
        print(row_dat)
        schedule_code = str(row_dat[0])
        team_name = row_dat[2]
        service_name = row_dat[3]
        time_quantum_name = row_dat[4]
        doctor_code = row_dat[5]
        amount = int(row_dat[11])
        team_obj = mongodb_ins.XHHK_Team.find_one({"name": team_name, "obsoleted": False, "app_id": ObjectId("5c9873929cc516000ecc4297")})
        if not team_obj:
            print("未找到科室：%s", team_name)
            continue
        date_p = time.mktime(time.strptime(row_dat[1], "%Y/%m/%d")) * 1000
        service_objs = mongodb_ins.YYPT_Service.find({
            "app_id": ObjectId("5c9873929cc516000ecc4297"),
            "date": date_p,
            "name": str(service_name),
            "obsoleted": False,
            "team_id": team_obj["_id"],
            "amount": int(amount),
            "his_schedule_code": {"$exists": False}
        })
        right_ser = None
        for ser in service_objs:
            time_quantum_obj = mongodb_ins.YYPT_TimeQuantum.find_one({"_id": ser["time_quantum_id"], "app_id": ObjectId("5c9873929cc516000ecc4297")})
            if time_quantum_obj.get("name") == time_quantum_name:
                if doctor_code and str(doctor_code) != "nan":
                    person_obj = mongodb_ins.XHHK_Person.find_one({"his_code": str(doctor_code), "obsoleted": False, "app_id": ObjectId("5c9873929cc516000ecc4297")})
                    ser_per_map = mongodb_ins.YYPT_ServicePerson.find_one({"service_id": ser["_id"]})
                    if person_obj["_id"] == ser_per_map["person_id"]:
                        right_ser = ser
                        break
                    else:
                        continue
                else:
                    right_ser = ser
                    break
        if not right_ser:
            print("未匹配到service: %s", row_dat)
            continue
        mongodb_ins.YYPT_Service.update_one({"_id": right_ser["_id"]},
                                            {"$set": {"his_schedule_code": str(schedule_code), "remark": "脚本更新his_schedule_code"}})
        print(111111, str(schedule_code))


def main():
    try:
        do_biz()
    except Exception:
        print(traceback.format_exc())


if __name__ == '__main__':
    main()
